package com.wangyu.talents.web.system.resource.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wangyu.talents.core.service.impl.BaseServiceImpl;
import com.wangyu.talents.web.system.resource.mapper.ResourceMapper;
import com.wangyu.talents.web.system.resource.model.Resource;
import com.wangyu.talents.web.system.resource.service.ResourceService;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 资源服务层实现
 *
 * @author wangyu
 * @Date 2018-09-04 14:46
 */
@Service("resourceService")
public class ResourceImpl extends BaseServiceImpl<Resource> implements ResourceService {

  @Autowired
  private ResourceMapper resourceMapper;

  @Override
  public List<Map<String, Object>> findRolePermissions(Long[] roleIds) {
    return resourceMapper.findRolePermissions(roleIds);
  }

  @Override
  public List<Resource> cascadeList(List<Resource> resList) {
    Map<Long, Resource> menuMap = Maps.newHashMap();
    for (Resource res : resList) {
      menuMap.put(res.getId(), res);
      if (res.getParentId() != 0L && menuMap.get(res.getParentId()) == null) {
        menuMap.put(res.getParentId(), this.get(res.getParentId()));
      }
    }

    List<Resource> rootList = Lists.newArrayList();
    for (Resource res : resList) {
      if (res.getParentId() != 0L) {
        Resource parent = menuMap.get(res.getParentId());
        if (parent != null) {
          parent.addChildren(res);
        }
      } else {
        rootList.add(res);
      }
    }
    return rootList;
  }

  @Override
  public List<Resource> getCascadeList() {
    return this.cascadeList(this.findAll());
  }
}
